package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserMapper;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.User;
import com.heima.admin.service.UserService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import com.heima.utils.common.AppJwtUtil;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 管理员登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.校验参数
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断这个用户是否存在
        User finduser = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getName, name));
        if (null == finduser) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //比对密码是否正确
        String finduserPassword = finduser.getPassword();
        String salt = finduser.getSalt();
        String md5pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
        if (!finduserPassword.equals(md5pwd)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }else {
            //密码正确,封装返回的参数,token和用户信息
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(finduser.getId().longValue()));
            finduser.setPassword("");
            finduser.setSalt("");
            map.put("user",finduser);
            return ResponseResult.okResult(map);
        }
    }
}
